import os
import random
import json
import base64
import http.client
import urllib.parse

from app import create_app
from app.extensions import db
from app.models.question import Question
from app.models.garbage_knowledge import GarbageKnowledge  # 新增导入

API_KEY = 'cfe6e6a802f6bb5f40b0b4bb2767a0c1'
IMAGE_DIR = '../garbage_train'
USED_FILE_PATH = 'used_images.txt'
NUM_QUESTIONS = 20

standard_options = {
    "A": "可回收物",
    "B": "有害垃圾",
    "C": "厨余垃圾",
    "D": "其他垃圾"
}

dic = {
    0: "可回收物",
    1: "有害垃圾",
    2: "厨余垃圾",
    3: "其他垃圾"
}


def classify_image_by_api(image_path):
    try:
        with open(image_path, 'rb') as f:
            img_bytes = f.read()
        img_base64 = base64.b64encode(img_bytes).decode()

        conn = http.client.HTTPSConnection('apis.tianapi.com')
        params = urllib.parse.urlencode({
            'key': API_KEY,
            'img': img_base64
        })
        headers = {'Content-type': 'application/x-www-form-urlencoded'}
        conn.request('POST', '/imglajifenlei/index', params, headers)

        res = conn.getresponse()
        result = json.loads(res.read().decode())
        conn.close()

        if (
            result.get("code") == 200 and
            "list" in result["result"] and
            len(result["result"]["list"]) > 0
        ):
            return result["result"]["list"]  # 返回整个 list
        else:
            print(f"[失败] API 响应异常：{result}")
            return []

    except Exception as e:
        print(f"[异常] 图像分类失败：{e}")
        return []


def load_used_images():
    if not os.path.exists(USED_FILE_PATH):
        return set()
    with open(USED_FILE_PATH, 'r') as f:
        return set(line.strip() for line in f.readlines())


def append_used_image(filename):
    with open(USED_FILE_PATH, 'a') as f:
        f.write(filename + '\n')


def save_to_knowledge(name, lajitype, tip):
    """
    将有效的知识项写入垃圾知识表
    """
    if not name or lajitype not in dic:
        return
    category = dic[lajitype]
    exists = GarbageKnowledge.query.filter_by(name=name).first()
    if not exists:
        knowledge = GarbageKnowledge(name=name, category=category, tip=tip)
        db.session.add(knowledge)
        print(f"📚 已保存知识项：{name} -> {category}")


def main():
    app = create_app()
    with app.app_context():
        all_files = [f for f in os.listdir(IMAGE_DIR) if f.lower().endswith('.jpg')]
        used_files = load_used_images()

        available_files = list(set(all_files) - used_files)
        if not available_files:
            print("❌ 没有可用图片，请检查 used_images.txt 或添加新图")
            return

        selected_files = random.sample(available_files, min(NUM_QUESTIONS, len(available_files)))
        success_count = 0

        for fname in selected_files:
            image_path = os.path.join(IMAGE_DIR, fname)
            results = classify_image_by_api(image_path)

            # 优先查找第一个有效分类作为题目
            selected_lajitype = None
            if results[0]["lajitype"] == 4:
                print(image_path)
            for item in results:
                name = item.get("name")
                lajitype = item.get("lajitype")
                tip = item.get("lajitip")
                if lajitype in [0, 1, 2, 3]:
                    save_to_knowledge(name, lajitype, tip)  # ✅ 保存到知识表
                    if selected_lajitype is None:
                        selected_lajitype = lajitype

            if selected_lajitype is None:
                print(f"跳过：{fname}，无有效分类")
                continue

            correct_letter = [k for k, v in standard_options.items() if v == dic[selected_lajitype]][0]
            q = Question(
                content_url=os.path.join("garbage_train", fname),
                name=name,
                options=standard_options,
                answer=correct_letter
            )
            exists = Question.query.filter_by(name=name).first()
            if not exists:
                db.session.add(q)

            append_used_image(fname)
            success_count += 1

        db.session.commit()
        print(f"✅ 成功导入 {success_count} 道题目，并保存知识项")

if __name__ == '__main__':
    main()
